import { useState, useEffect } from 'react'
import { Button, Input, Card, Modal, Loading } from './index'
import { request, api, useRequest, usePagination } from '../utils'

// 临时接口定义
interface ArticleItem {
  id: number | string
  title: string
  author: string
  status: string
  createdAt: string
  summary?: string
}

const RequestDemo = () => {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [globalLoading, setGlobalLoading] = useState(false)
  const [errorMessage, setErrorMessage] = useState('')
  const [uploadProgress, setUploadProgress] = useState(0)

  // 设置全局 loading 和错误处理
  useEffect(() => {
    request.setLoadingCallback((loading) => setGlobalLoading(loading))
    request.setErrorCallback((error) => {
      setErrorMessage(error)
      setTimeout(() => setErrorMessage(''), 3000)
    })
  }, [])

  // 使用 useRequest Hook 获取用户信息
  const {
    data: userInfo,
    loading: userLoading,
    error: userError,
    run: getUserInfo,
    refresh: refreshUserInfo
  } = useRequest(() => api.user.getUserInfo(), {
    manual: true, // 手动触发
    onSuccess: (data) => {
      console.log('获取用户信息成功:', data)
    },
    onError: (error) => {
      console.log('获取用户信息失败:', error)
    }
  })

  // 使用 usePagination Hook 获取文章列表
  const {
    data: articles,
    loading: articlesLoading,
    pagination,
    changePage,
    changePageSize,
    reload: reloadArticles
  } = usePagination(
    (params) => api.article.getList(params),
    {
      defaultCurrent: 1,
      defaultPageSize: 5,
      onSuccess: (data) => {
        console.log('获取文章列表成功:', data)
      }
    }
  )

  // 登录表单
  const [loginForm, setLoginForm] = useState({
    username: 'demo@example.com',
    password: '123456'
  })

  // 手动调用 API 示例
  const handleLogin = async () => {
    try {
      const response = await api.user.login(loginForm)
      console.log('登录成功:', response.data)
      
      // 保存 token
      localStorage.setItem('token', response.data.token)
      
      // 获取用户信息
      getUserInfo()
      
      alert('登录成功！')
    } catch (error) {
      console.error('登录失败:', error)
    }
  }

  // 文件上传示例
  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    try {
      setUploadProgress(0)
      const response = await api.file.uploadFile(file, (progress) => {
        setUploadProgress(progress)
      })
      
      console.log('文件上传成功:', response.data)
      alert(`文件上传成功: ${response.data.filename}`)
      setUploadProgress(0)
    } catch (error) {
      console.error('文件上传失败:', error)
      setUploadProgress(0)
    }
  }

  // 批量操作示例
  const handleBatchDelete = async () => {
    if (!articles || articles.length === 0) {
      alert('没有可删除的文章')
      return
    }

    const confirmDelete = confirm(`确定要删除前3篇文章吗？`)
    if (!confirmDelete) return

    try {
      const idsToDelete = articles.slice(0, 3).map((article: ArticleItem) => article.id)
      await api.article.batchDelete(idsToDelete)
      alert('批量删除成功')
      reloadArticles()
    } catch (error) {
      console.error('批量删除失败:', error)
    }
  }

  // 下载示例
  const handleDownload = async () => {
    try {
      await request.download('/api/export/articles', 'articles.xlsx')
      alert('下载开始')
    } catch (error) {
      console.error('下载失败:', error)
    }
  }

  return (
    <div className="space-y-6">
      {/* 全局 Loading */}
      {globalLoading && (
        <div className="fixed top-20 right-6 z-50 animate-fade-in">
          <div className="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-5 py-3 rounded-xl flex items-center space-x-3 shadow-xl border border-blue-400/50 backdrop-blur-sm">
            <Loading size="sm" type="spinner" />
            <span className="font-medium">请求中...</span>
          </div>
        </div>
      )}

      {/* 错误提示 */}
      {errorMessage && (
        <div className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50">
          <div className="bg-gradient-to-r from-red-500 to-red-600 text-white px-6 py-3 rounded-xl shadow-2xl border border-red-400/50 backdrop-blur-sm">
            <div className="flex items-center space-x-2">
              <span className="font-semibold">⚠️</span>
              <span className="font-medium">{errorMessage}</span>
            </div>
          </div>
        </div>
      )}

      {/* 用户信息卡片 */}
      <Card title="用户信息管理" subtitle="使用 useRequest Hook">
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Input
              label="用户名/邮箱"
              value={loginForm.username}
              onChange={(e) => setLoginForm({ ...loginForm, username: e.target.value })}
              placeholder="请输入用户名或邮箱"
            />
            <Input
              label="密码"
              type="password"
              value={loginForm.password}
              onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })}
              placeholder="请输入密码"
            />
          </div>

          <div className="flex space-x-4">
            <Button onClick={handleLogin} loading={userLoading}>
              登录
            </Button>
            <Button variant="outline" onClick={refreshUserInfo} disabled={!userInfo}>
              刷新用户信息
            </Button>
          </div>

          {userInfo && (
            <div className="bg-gradient-to-br from-green-50 to-emerald-50 p-5 rounded-xl border border-green-200 shadow-sm">
              <h4 className="font-bold text-green-800 mb-3 flex items-center gap-2">
                <span>✅</span>
                用户信息
              </h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                <div className="flex items-center space-x-2">
                  <span className="font-semibold text-gray-600">ID:</span>
                  <span className="text-gray-900 font-medium">{userInfo.id}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <span className="font-semibold text-gray-600">用户名:</span>
                  <span className="text-gray-900 font-medium">{userInfo.username}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <span className="font-semibold text-gray-600">邮箱:</span>
                  <span className="text-gray-900 font-medium">{userInfo.email}</span>
                </div>
                <div className="flex items-center space-x-2">
                  <span className="font-semibold text-gray-600">角色:</span>
                  <span className="px-2 py-1 bg-green-100 text-green-700 rounded-lg text-xs font-bold">
                    {userInfo.roleName || userInfo.roleKey || '—'}
                  </span>
                </div>
                <div className="flex items-center space-x-2">
                  <span className="font-semibold text-gray-600">权限:</span>
                  <span className="text-gray-900 font-medium">
                    {userInfo.permissions?.includes('*')
                      ? '全部权限'
                      : (userInfo.permissions && userInfo.permissions.length
                          ? userInfo.permissions.join(', ')
                          : '—')}
                  </span>
                </div>
              </div>
            </div>
          )}

          {userError && (
            <div className="bg-gradient-to-br from-red-50 to-pink-50 p-5 rounded-xl border border-red-200 shadow-sm">
              <div className="flex items-center space-x-2 text-red-700 font-semibold">
                <span>❌</span>
                <span>错误: {userError.message}</span>
              </div>
            </div>
          )}
        </div>
      </Card>

      {/* 文章列表卡片 */}
      <Card title="文章列表管理" subtitle="使用 usePagination Hook">
        <div className="space-y-4">
          <div className="flex justify-between items-center">
            <div className="flex space-x-2">
              <Button variant="outline" onClick={reloadArticles}>
                刷新列表
              </Button>
              <Button variant="danger" onClick={handleBatchDelete}>
                批量删除前3篇
              </Button>
              <Button variant="secondary" onClick={handleDownload}>
                导出 Excel
              </Button>
            </div>
            
            <div className="flex items-center space-x-2">
              <span className="text-sm font-medium text-gray-600">每页显示:</span>
              <select
                value={pagination.pageSize}
                onChange={(e) => changePageSize(Number(e.target.value))}
                className="border border-gray-300 rounded-lg px-3 py-2 text-sm font-medium bg-white hover:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-500/50 transition-all duration-200"
              >
                <option value={5}>5</option>
                <option value={10}>10</option>
                <option value={20}>20</option>
              </select>
            </div>
          </div>

          {articlesLoading ? (
            <div className="flex justify-center py-8">
              <Loading type="spinner" text="加载中..." />
            </div>
          ) : articles && articles.length > 0 ? (
            <div className="space-y-2">
              {articles.map((article: ArticleItem, index: number) => (
                <div key={article.id} className="border border-gray-200 rounded-xl p-5 bg-gradient-to-r from-white to-gray-50/50 hover:from-blue-50/50 hover:to-purple-50/50 transition-all duration-200 group shadow-sm hover:shadow-md">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <h4 className="font-bold text-gray-900 mb-2 group-hover:text-blue-600 transition-colors duration-200">
                        <span className="inline-block w-6 h-6 bg-blue-100 text-blue-600 rounded-lg text-xs font-bold mr-2 text-center leading-6">
                          {index + 1}
                        </span>
                        {article.title}
                      </h4>
                      <p className="text-sm text-gray-600 mb-2">
                        <span className="font-medium">作者:</span> {article.author} | 
                        <span className="font-medium"> 状态:</span> 
                        <span className={`ml-1 px-2 py-0.5 rounded-lg text-xs font-semibold ${
                          article.status === '已发布' ? 'bg-green-100 text-green-700' : 
                          article.status === '草稿' ? 'bg-yellow-100 text-yellow-700' : 
                          'bg-gray-100 text-gray-700'
                        }`}>
                          {article.status}
                        </span> | 
                        <span className="font-medium"> 创建时间:</span> {article.createdAt}
                      </p>
                      {article.summary && (
                        <p className="text-sm text-gray-700 mt-2 p-3 bg-gray-50 rounded-lg border border-gray-100">
                          {article.summary}
                        </p>
                      )}
                    </div>
                    <div className="flex space-x-2 ml-4">
                      <Button size="sm" variant="outline">编辑</Button>
                      <Button size="sm" variant="danger">删除</Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              暂无文章数据
            </div>
          )}

          {/* 分页 */}
          {pagination.totalPages > 1 && (
            <div className="flex justify-between items-center mt-4">
              <div className="text-sm text-gray-600">
                共 {pagination.total} 条记录，第 {pagination.current} / {pagination.totalPages} 页
              </div>
              <div className="flex space-x-2">
                <Button
                  size="sm"
                  variant="outline"
                  disabled={pagination.current <= 1}
                  onClick={() => changePage(pagination.current - 1)}
                >
                  上一页
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  disabled={pagination.current >= pagination.totalPages}
                  onClick={() => changePage(pagination.current + 1)}
                >
                  下一页
                </Button>
              </div>
            </div>
          )}
        </div>
      </Card>

      {/* 文件上传卡片 */}
      <Card title="文件上传管理" subtitle="支持进度显示和批量上传">
        <div className="space-y-4">
          <div className="flex flex-col space-y-2">
            <label className="text-sm font-medium text-gray-700">
              选择文件上传:
            </label>
            <input
              type="file"
              onChange={handleFileUpload}
              className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
            />
          </div>

          {uploadProgress > 0 && uploadProgress < 100 && (
            <div className="space-y-3 p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-xl border border-blue-200">
              <div className="flex justify-between text-sm font-semibold">
                <span className="text-gray-700">上传进度</span>
                <span className="text-blue-600">{uploadProgress}%</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-3 overflow-hidden shadow-inner">
                <div
                  className="bg-gradient-to-r from-blue-500 to-purple-600 h-3 rounded-full transition-all duration-300 shadow-sm relative overflow-hidden"
                  style={{ width: `${uploadProgress}%` }}
                >
                  <div className="absolute inset-0 bg-white/30 animate-pulse"></div>
                </div>
              </div>
            </div>
          )}
        </div>
      </Card>

      {/* API 使用说明 */}
      <Card title="API 使用说明" subtitle="请求库功能特性">
        <div className="space-y-4">
          <Button onClick={() => setIsModalOpen(true)}>
            查看详细文档
          </Button>

          <div className="grid md:grid-cols-2 gap-6 text-sm">
            <div className="p-4 bg-gradient-to-br from-blue-50 to-blue-100/50 rounded-xl border border-blue-200">
              <h4 className="font-bold mb-3 text-blue-800 flex items-center gap-2">
                <span>✨</span>
                核心特性
              </h4>
              <ul className="space-y-2 text-gray-700">
                <li className="flex items-start gap-2">
                  <span className="text-blue-500 mt-1">•</span>
                  <span>自动请求/响应拦截器</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-blue-500 mt-1">•</span>
                  <span>统一错误处理和提示</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-blue-500 mt-1">•</span>
                  <span>全局 Loading 状态管理</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-blue-500 mt-1">•</span>
                  <span>JWT Token 自动处理</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-blue-500 mt-1">•</span>
                  <span>文件上传/下载支持</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-blue-500 mt-1">•</span>
                  <span>请求重试和取消</span>
                </li>
              </ul>
            </div>
            
            <div className="p-4 bg-gradient-to-br from-purple-50 to-purple-100/50 rounded-xl border border-purple-200">
              <h4 className="font-bold mb-3 text-purple-800 flex items-center gap-2">
                <span>🚀</span>
                React Hooks
              </h4>
              <ul className="space-y-2 text-gray-700">
                <li className="flex items-start gap-2">
                  <span className="text-purple-500 mt-1">•</span>
                  <span>useRequest - 通用请求管理</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-purple-500 mt-1">•</span>
                  <span>usePagination - 分页数据管理</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-purple-500 mt-1">•</span>
                  <span>防抖和节流支持</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-purple-500 mt-1">•</span>
                  <span>自动依赖刷新</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-purple-500 mt-1">•</span>
                  <span>成功/失败回调</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="text-purple-500 mt-1">•</span>
                  <span>数据缓存和更新</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </Card>

      {/* 文档弹窗 */}
      <Modal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        title="请求库使用文档"
        size="lg"
      >
        <div className="space-y-6">
          <div>
            <h3 className="font-semibold mb-2">基础使用</h3>
            <div className="bg-gray-100 p-3 rounded text-sm font-mono">
              <pre>{`// 导入
import { request, api, useRequest } from './utils'

// 直接调用 API
const response = await api.user.login({ username, password })

// 使用 Hook
const { data, loading, error, run } = useRequest(() => api.user.getUserInfo())`}</pre>
            </div>
          </div>

          <div>
            <h3 className="font-semibold mb-2">分页使用</h3>
            <div className="bg-gray-100 p-3 rounded text-sm font-mono">
              <pre>{`// 分页 Hook
const { 
  data, 
  loading, 
  pagination, 
  changePage 
} = usePagination((params) => api.article.getList(params))`}</pre>
            </div>
          </div>

          <div>
            <h3 className="font-semibold mb-2">自定义配置</h3>
            <div className="bg-gray-100 p-3 rounded text-sm font-mono">
              <pre>{`// 请求配置
await request.post('/api/users', data, {
  showLoading: false,  // 不显示全局 loading
  showError: false,    // 不显示错误提示
  timeout: 5000        // 自定义超时
})`}</pre>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default RequestDemo
